package com.app.core.base;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

/**
 * 
 * 
 * @since v#{version}
 * @author zhangxf
 * @created 2015年10月24日 下午4:57:34
 */
public class BaseController {

    private static final Logger log = LoggerFactory.getLogger(BaseController.class);

    /**
     * 文件导出,返回下载文件
     */
    public ResponseEntity<byte[]> fileExport(String filePath) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> responseEntity = null;
        try {
            // 下载文件名转为ISO-8859-1，避免中文乱码
            headers.setContentDispositionFormData("attachment",
                new String(filePath.substring(filePath.lastIndexOf("/") + 1).getBytes("GBK"), "ISO-8859-1"));
            responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(filePath)), headers,
                HttpStatus.CREATED);
        } catch (UnsupportedEncodingException e) {
            responseEntity = new ResponseEntity<byte[]>("文件下载异常.".getBytes(), headers, HttpStatus.CREATED);
            log.error("文件下载异常: {}", filePath, e);
        } catch (IOException e) {
            responseEntity = new ResponseEntity<byte[]>("文件下载异常.".getBytes(), headers, HttpStatus.CREATED);
            log.error("文件下载异常: {}", filePath, e);
        }

        return responseEntity;
    }

}
